import { PrismaClient } from '@prisma/client';
import * as fs from 'fs';
import * as path from 'path';
import * as https from 'https';
import * as http from 'http';
import { uploadFile } from '../src/lib/storage';
import { randomUUID } from 'crypto';

const prisma = new PrismaClient();

interface Website {
  id: string;
  name: string;
  description: string;
  url: string;
  imageUrl: string;
  imagePath: string;
  categoryId: string;
  status: string;
  sortOrder: number;
  createdAt: string;
  updatedAt: string;
  category: {
    id: string;
    name: string;
  };
}

interface Category {
  id: string;
  name: string;
  mainCategoryId: string;
  type: string;
  parentId: string | null;
  level: number;
  path: string | null;
  isLeaf: boolean;
  sortOrder: number;
  icon: string | null;
  createdAt: string;
  updatedAt: string;
  children: any[];
  websites: Website[];
}

interface MainCategory {
  id: string;
  name: string;
  type: string;
  sortOrder: number;
  createdAt: string;
  updatedAt: string;
  categories: Category[];
}

type NavData = MainCategory[];

// 下载图片并返回Buffer
async function downloadImage(imageUrl: string): Promise<Buffer | null> {
  return new Promise((resolve) => {
    const client = imageUrl.startsWith('https:') ? https : http;
    
    client.get(imageUrl, (response) => {
      if (response.statusCode !== 200) {
        console.warn(`⚠️  下载图片失败: ${imageUrl} (状态码: ${response.statusCode})`);
        resolve(null);
        return;
      }

      const chunks: Buffer[] = [];
      response.on('data', (chunk) => chunks.push(chunk));
      response.on('end', () => resolve(Buffer.concat(chunks)));
    }).on('error', (error) => {
      console.warn(`⚠️  下载图片失败: ${imageUrl} (错误: ${error.message})`);
      resolve(null);
    });
  });
}

// 上传图片到MinIO并创建文件记录
async function uploadImageToMinio(imageBuffer: Buffer, originalUrl: string): Promise<string | null> {
  try {
    // 从URL中提取文件扩展名
    const urlPath = new URL(originalUrl).pathname;
    const extension = path.extname(urlPath) || '.png';
    const objectKey = `${randomUUID()}${extension}`;
    
    // 上传到MinIO
    const stored = await uploadFile(imageBuffer, objectKey, 'ai-tools/');
    
    // 创建文件记录
    const fileRecord = await prisma.file.create({
      data: {
        provider: 'minio',
        bucket: process.env.MINIO_BUCKET_NAME || 'kason-world',
        path: stored.path,
        url: stored.url,
        mimeType: stored.mimeType,
        size: stored.size,
        visibility: 'public',
        category: 'ai-tool-icon',
        source: 'ai-nav-import',
        status: 'active'
      }
    });
    
    console.log(`✅ 图片上传成功: ${originalUrl} -> ${stored.url}`);
    return fileRecord.id;
  } catch (error) {
    console.error(`❌ 上传图片失败: ${originalUrl}`, error);
    return null;
  }
}

// 处理图片：下载并上传到MinIO
async function processImage(imageUrl: string): Promise<string | null> {
  if (!imageUrl || !imageUrl.startsWith('http')) {
    console.warn(`⚠️  无效的图片URL: ${imageUrl}`);
    return null;
  }

  const imageBuffer = await downloadImage(imageUrl);
  if (!imageBuffer) {
    return null;
  }

  return await uploadImageToMinio(imageBuffer, imageUrl);
}

// 获取或创建分类
async function getOrCreateCategory(categoryName: string, menuId: string): Promise<string> {
  // 先查找是否已存在同名分类
  const existingCategory = await prisma.category.findFirst({
    where: {
      name: categoryName,
      menuId: menuId
    }
  });

  if (existingCategory) {
    console.log(`📂 分类已存在: ${categoryName}`);
    return existingCategory.id;
  }

  // 创建新分类
  const newCategory = await prisma.category.create({
    data: {
      name: categoryName,
      menuId: menuId
    }
  });

  console.log(`📂 创建新分类: ${categoryName}`);
  return newCategory.id;
}

// 创建内容
async function createContent(website: Website, categoryId: string): Promise<void> {
  try {
    // 处理图片
    let coverId: string | null = null;
    if (website.imageUrl) {
      coverId = await processImage(website.imageUrl);
    }

    // 创建内容
    const content = await prisma.content.create({
      data: {
        title: website.name,
        content: website.description,
        summary: website.description,
        url: website.url,
        type: 1, // 1-网站
        coverId: coverId
      }
    });

    // 关联分类
    await prisma.contentCategory.create({
      data: {
        contentId: content.id,
        categoryId: categoryId
      }
    });

    console.log(`✅ 创建内容: ${website.name}`);
  } catch (error) {
    console.error(`❌ 创建内容失败: ${website.name}`, error);
  }
}

// 主导入函数
async function importAiNavData() {
  try {
    console.log('🚀 开始导入AI工具导航数据...');

    // 读取JSON文件
    const jsonPath = path.join(process.cwd(), 'ai-nav.json');
    if (!fs.existsSync(jsonPath)) {
      throw new Error(`找不到文件: ${jsonPath}`);
    }

    const jsonData = fs.readFileSync(jsonPath, 'utf-8');
    const navData: NavData = JSON.parse(jsonData);

    // 获取AI工具导航菜单
    const aiToolsMenu = await prisma.menu.findFirst({
      where: { sysCode: 'ai_tools_nav' }
    });

    if (!aiToolsMenu) {
      throw new Error('找不到AI工具导航菜单，请先运行初始化脚本');
    }

    console.log(`📋 找到AI工具导航菜单: ${aiToolsMenu.name}`);

    // 统计信息
    let totalCategories = 0;
    let totalItems = 0;
    let processedItems = 0;

    // 遍历主分类（如"AI工具箱"）
    for (const mainCategory of navData) {
      console.log(`\n🔄 处理主分类: ${mainCategory.name}`);
      
      // 遍历子分类（如"对话聊天"、"文案写作"等）
      for (const category of mainCategory.categories) {
        console.log(`\n  🔄 处理子分类: ${category.name}`);
        totalCategories++;
        
        // 获取或创建分类
        const categoryId = await getOrCreateCategory(category.name, aiToolsMenu.id);
        
        // 处理该分类下的所有工具
        for (const website of category.websites) {
          totalItems++;
          console.log(`    🔄 处理工具: ${website.name}`);
          
          // 检查是否已存在相同URL的内容
          const existingContent = await prisma.content.findFirst({
            where: { url: website.url }
          });

          if (existingContent) {
            console.log(`    ⏭️  工具已存在，跳过创建: ${website.name}`);
            // 若已有内容缺少摘要，则补充
            if (!existingContent.summary || existingContent.summary.trim() === '') {
              await prisma.content.update({
                where: { id: existingContent.id },
                data: { summary: website.description }
              });
              console.log(`    ✏️  已补充摘要: ${website.name}`);
            }
            continue;
          }

          await createContent(website, categoryId);
          processedItems++;
          
          // 添加延迟，避免请求过于频繁
          await new Promise(resolve => setTimeout(resolve, 500));
        }
      }
    }

    console.log('\n🎉 导入完成！');
    console.log(`📊 统计信息:`);
    console.log(`   - 总分类数: ${totalCategories}`);
    console.log(`   - 总工具数: ${totalItems}`);
    console.log(`   - 成功导入: ${processedItems}`);
    console.log(`   - 跳过重复: ${totalItems - processedItems}`);

  } catch (error) {
    console.error('❌ 导入失败:', error);
    throw error;
  }
}

// 主函数
async function main() {
  try {
    await importAiNavData();
  } catch (error) {
    console.error('❌ 脚本执行失败:', error);
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  main();
}

export { importAiNavData };